package models

import (
	"fmt"
	"git.inedcn.com/ined/cmn"
	"log"
	"rongyy/src/app"
	"time"
)

type InvoiceList struct {
	InvoiceNo   string `json:"invoice_no"`
	InvoiceAmt  string `json:"invoice_amt"`
	InsuFlag    string `json:"insu_flag"`
	OutInsuInfo string `json:"out_insu_info"`
	HisInsuInfo string `json:"his_insu_info"`
}
type ItemList struct {
	ItemCode     string `json:"item_code"`
	ItemName     string `json:"item_name"`
	ItemCategory string `json:"item_category"`
	ItemRecDept  string `json:"item_rec_dept"`
	ItemPrice    string `json:"item_price"`
	ItemQty      string `json:"item_qty"`
	ItemSum      string `json:"item_sum"`
	ItemUom      string `json:"item_uom"`
	ItemSpecs    string `json:"item_specs"`
}
type PrescriptionModel struct {
	BaseModel      `xorm:"extends"`
	OrderNo        string     `json:"order_no"`       // 生成的订单号
	OrderSum       string     `json:"order_sum"`      // 状态 0启用 1停用
	InvoiceList    []Invoice  `json:"invoice_list"`   // 0 默认值 1删除
	ItemList       []ItemList `json:"item_list"`      // 创建时间
	OrderInsType   string     `json:"order_ins_type"` // 创建时间
	OrderSn        string     `json:"order_sn"`       // 创建时间
	PatientId      string     `json:"patient_id"`     // 创建人
	CardNo         string     `json:"card_no"`        // 卡号用于his完成支付要传
	PayUnionid     string     `json:"pay_unionid"`    // 创建人
	Status         string     `json:"status"`         // -2已退费 -1取消预结算 0创建 1成功
	PayStatus      string     `json:"pay_status"`     // -1支付失败  0待支付 1支付中 2支付成功
	RefundSn       string     `json:"refund_sn"`      // 更新his失败以后，退费单号
	UpdatedBy      string     `json:"updated_by"`     // bank为支付平台 mp为小程序
	Hospital       string     `json:"hospital" xorm:"-"`
	RefundFee      float64    `json:"refund_fee" xorm:"-"`
	TotalRefundFee float64    `json:"total_refund_fee"` // 总退费
	Remark         string     `json:"remark"`
	Openid         string     `json:"openid"  xorm:"-"`
	InvoiceNo      string     `json:"invoice_no"`
	AdmNo          string     `json:"adm_no"`
	OrderInsuFlag  string     `json:"order_insu_flag"`
	OrdInsuData    string     `json:"ord_insu_data"`
	PayOrdList     []PayOrder `json:"pay_ord_list"`
}

type OpPreModel struct {
	BaseModel   `xorm:"extends"`
	OrderNo     string     `json:"order_no"`     // 生成的订单号
	InvoiceList []Invoice  `json:"invoice_list"` // 0 默认值 1删除
	ItemList    []ItemList `json:"item_list"`    // 创建时间
	PatientId   string     `json:"patient_id"`   // 创建人
	Status      string     `json:"status"`       // -2已退费 -1取消预结算 0创建 1成功
	InvoiceNo   string     `json:"invoice_no"`
	OrderSn     string     `json:"order_sn"`
}

type OpCancelManualReq struct {
	CardNo       string `json:"card_no"`
	PatientId    string `json:"patient_id"`
	InvoiceNoStr string `json:"invoice_no_str"`
	OrderNo      string `json:"order_no"`
	OrderSn      string `json:"order_sn"`
}

type DbzQuery struct {
	Hospital string       `json:"hospital" xorm:"-"`
	Start    cmn.JsonTime `json:"start"` // 创建时间
	End      cmn.JsonTime `json:"end"`   // 更新时间
}

type OpCompleteLogModel struct {
	Id         int64        `xorm:"pk autoincr" json:"id"`
	Info       string       `json:"info"`
	OrderSn    string       `json:"order_sn"`
	ResultCode string       `json:"result_code"`
	CreatedAt  cmn.JsonTime `xorm:"created" json:"created_at"`  // 创建时间
	UpdatedAt  cmn.JsonTime `xorm:"updated"  json:"updated_at"` // 更新时间
	Hospital   string       `json:"hospital" xorm:"-"`
}

func (pm *PrescriptionModel) TableName() string {
	return "pres_orders"
}

func (pm *PrescriptionModel) String() string {
	return fmt.Sprintf("userid")
}

func (pm *PrescriptionModel) Create() error {
	_, err := app.DB().Insert(pm)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (pm *PrescriptionModel) FindByOrderSn(orderSn string) (*PrescriptionModel, bool, error) {
	pres := new(PrescriptionModel)
	has, err := app.DB().Where("order_sn = ?", orderSn).Get(pres)
	if err != nil {
		return nil, has, err
	}
	return pres, has, nil
}

func (pm *PrescriptionModel) FindByOrderNo(orderNo string) (*PrescriptionModel, bool, error) {
	pres := new(PrescriptionModel)
	has, err := app.DB().Where("order_no = ?", orderNo).Limit(1).Desc("updated_at").Get(pres)
	if err != nil {
		return nil, has, err
	}
	return pres, has, nil
}

func (pm *PrescriptionModel) FindByAdm(admNo string) (*PrescriptionModel, bool, error) {
	pres := new(PrescriptionModel)
	has, err := app.DB().Where("adm_no = ?", admNo).Limit(1).Desc("updated_at").Get(pres)
	if err != nil {
		return nil, has, err
	}
	return pres, has, nil
}

func (pm *PrescriptionModel) FindByAdmAndInvoice(admNo string, invoiceNo string) (*PrescriptionModel, bool, error) {
	pres := new(PrescriptionModel)
	has, err := app.DB().Where("adm_no = ? and invoice_no", admNo, invoiceNo).Limit(1).Desc("updated_at").Get(pres)
	if err != nil {
		return nil, has, err
	}
	return pres, has, nil
}

func (rm *PrescriptionModel) UpdateRefund(opOrder *PrescriptionModel) error {
	_, err := app.DB().Where("order_sn = ?", opOrder.OrderSn).Cols("remark", "pay_status", "refund_sn").Update(opOrder)
	if err != nil {
		return err
	}
	return err
}

//
//func (pm *PrescriptionModel) ConfirmOrder(orderSn string, updatedBy string, hospital string) error {
//	pres := new(PrescriptionModel)
//	pres.Status = 1
//	pres.PayStatus = 2
//	pres.UpdatedBy = updatedBy
//	_, err := app.DB().Where("order_sn = ?", orderSn).Cols("status", "pay_status", "updated_by", "updated_at").Update(pres)
//	if err != nil {
//		return err
//	}
//	return nil
//}
//
//func (pm *PrescriptionModel) CancelPreOrder(orderSn string, hospital string) error {
//	pres := new(PrescriptionModel)
//	pres.Status = -1
//	pres.PayStatus = -1
//	_, err := app.DB().Where("order_sn = ?", orderSn).Cols("status", "pay_status", "updated_at").Update(pres)
//	if err != nil {
//		return err
//	}
//	return nil
//}
//
//func (pm *PrescriptionModel) CancelPreOrderByNo(orderNo string, hospital string) error {
//	pres := new(PrescriptionModel)
//	has, err := app.DB().Where("order_no = ?", orderNo).Limit(1).Desc("updated_at").Get(pres)
//	if !has {
//		return fmt.Errorf("订单不存在")
//	}
//	pres.Status = -1
//	pres.PayStatus = -1
//	_, err = app.DB().Where("order_sn = ?", pres.OrderSn).Cols("status", "pay_status", "updated_at").Update(pres)
//	if err != nil {
//		return err
//	}
//	return nil
//}
//
//// 支付失败
//func (rm *RegisterModel) payFailed(orderSn string, hospital string) error {
//	reg := &RegisterModel{}
//	reg.PayStatus = -1
//	_, err := app.DB().Where("order_sn = ? and pay_status = 1 and status = 0", orderSn).Cols("pay_status", "updated_at").Update(reg)
//	if err != nil {
//		return err
//	}
//	return err
//}
//
//func (pm *PrescriptionModel) RefundOrder(orderSn string, hospital string) error {
//	pres := new(PrescriptionModel)
//	pres.Status = -2
//	_, err := app.DB().Where("order_sn = ?", orderSn).Cols("status").Update(pres)
//	if err != nil {
//		return err
//	}
//	return nil
//}
//
//func (pm *PrescriptionModel) SavePrecRefund(orderSn string, refundSn string, totalRefundFee float64, hospital string) error {
//	pres := new(PrescriptionModel)
//	pres.Status = -2
//	pres.RefundSn = refundSn
//	pres.TotalRefundFee = totalRefundFee
//	_, err := app.DB().Where("order_sn = ?", orderSn).Cols("refund_sn", "total_refund_fee", "status", "updated_at").Update(pres)
//	if err != nil {
//		return err
//	}
//	return nil
//}

func (pm *PrescriptionModel) QueryPayingPresOrderInOneMin(unionid string, hospital string) (*PrescriptionModel, bool, error) {
	pres := new(PrescriptionModel)
	has, err := app.DB().Where("pay_unionid = ? and pay_status = 1 and updated_at >=DATE_SUB(NOW(),INTERVAL 1 MINUTE)", unionid).Get(pres)
	if err != nil {
		return nil, false, err
	}
	return pres, has, nil
}

func (pm *PrescriptionModel) QueryAfterOneMin(patient_id string, hospital string) ([]PrescriptionModel, int64, error) {
	pres := make([]PrescriptionModel, 0)
	total, err := app.DB().Where("patient_id = ? and pay_status < 2 and updated_at < DATE_SUB(NOW(),INTERVAL 1 MINUTE) and updated_at > DATE_SUB(NOW(),INTERVAL 24 HOUR)", patient_id).FindAndCount(&pres)
	if err != nil {
		return nil, 0, err
	}
	return pres, total, nil
}

func (pm *PrescriptionModel) QueryPrepay(patient_id string) ([]PrescriptionModel, int64, error) {
	pres := make([]PrescriptionModel, 0)
	total, err := app.DB().Where("patient_id = ? and status = 'prepay' and pay_status = 'paying' and updated_at < DATE_SUB(NOW(),INTERVAL 1 MINUTE) and updated_at > DATE_SUB(NOW(),INTERVAL 24 HOUR)", patient_id).FindAndCount(&pres)
	if err != nil {
		return nil, 0, err
	}
	return pres, total, nil
}

//
//func (pm *PrescriptionModel) UpdatePresToPaying(orderSn string, orderNo string, hospital string) error {
//	pres := &PrescriptionModel{}
//	pres.PayStatus = 1
//	_, err := app.DB().Where("order_sn = ? and order_no = ?", orderSn, orderNo).Cols("pay_status", "updated_at").Update(pres)
//	if err != nil {
//		return err
//	}
//	return nil
//}

func (pm *PrescriptionModel) UpdateRemark(orderSn string, remark string, hospital string) error {
	pres := &PrescriptionModel{}
	pres.Remark = remark
	_, err := app.DB().Where("order_sn = ?", orderSn).Cols("remark", "updated_at").Update(pres)
	if err != nil {
		return err
	}
	return nil
}

func (pm *PrescriptionModel) InsertCompleteLog(pres *OpCompleteLogModel) error {
	_, err := app.DB().Table("op_complete_log").Insert(pres)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (rm *PrescriptionModel) QueryUnconfirmOrder() ([]PrescriptionModel, int64, error) {
	regs := make([]PrescriptionModel, 0)
	local, _ := time.LoadLocation("Asia/Shanghai")
	t := time.Now().In(local).Format("2006-01-02 15:04:05")
	total, err := app.DB().Where("status = 'prepay' and pay_status = 'paying' and TIMESTAMPDIFF( MINUTE, created_at, ? ) < 5", t).Limit(999, 0).FindAndCount(&regs)
	if err != nil {
		return nil, 0, err
	}
	return regs, total, err
}

func (rm *PrescriptionModel) Dbzquery(hospital string, time1 cmn.JsonTime, time2 cmn.JsonTime) ([]PrescriptionModel, int64, error) {
	regs := make([]PrescriptionModel, 0)
	total, err := app.DB().Where("status = 0 and pay_status = 1 and updated_at > ? and updated_at < ?", time1, time2).Limit(999, 0).FindAndCount(&regs)
	if err != nil {
		return nil, 0, err
	}
	return regs, total, err
}

func (pm *PrescriptionModel) Confirm() error {
	_, err := app.DB().Where("order_sn = ? and order_no=? and patient_id=? and invoice_no=?", pm.OrderSn, pm.OrderNo, pm.PatientId, pm.InvoiceNo).Cols("status", "pay_status", "updated_by").Update(pm)
	if err != nil {
		return err
	}
	return nil
}

func (pm *PrescriptionModel) CancelPreOrder() error {
	pm.Status = "canceled"
	_, err := app.DB().Where("invoice_no=? and patient_id=? and order_sn=? ", pm.InvoiceNo, pm.PatientId, pm.OrderSn).Cols("status").Update(pm)
	if err != nil {
		return err
	}
	return nil
}

func (pm *PrescriptionModel) CreatePre(opm *OpPreModel) error {
	_, err := app.DB().Table("pres_order_precheck").Insert(opm)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (pm *PrescriptionModel) FindPreByOrderNo(orderNo string) (*OpPreModel, bool, error) {
	pres := new(OpPreModel)
	has, err := app.DB().Table("pres_order_precheck").Where("order_no = ?", orderNo).Limit(1).Desc("updated_at").Get(pres)
	if err != nil {
		return nil, has, err
	}
	return pres, has, nil
}

func (pm *PrescriptionModel) FindPreByPatientId(pid string) ([]OpPreModel, int64, error) {
	pres := make([]OpPreModel, 0)
	total, err := app.DB().Table("pres_order_precheck").Where("patient_id=? and status=? and updated_at < DATE_SUB(NOW(),INTERVAL 2 MINUTE) and updated_at > DATE_SUB(NOW(),INTERVAL 24 HOUR)", pid, "charge").Desc("updated_at").FindAndCount(&pres)
	if err != nil {
		return nil, total, err
	}
	return pres, total, nil
}

func (pm *PrescriptionModel) UpdatePre(opm *OpPreModel) error {
	_, err := app.DB().Table("pres_order_precheck").Where("order_no=? and invoice_no = ?", opm.OrderNo, opm.InvoiceNo).Cols("status", "invoice_no", "order_sn").Update(opm)
	if err != nil {
		return err
	}
	return nil
}
